/*
	This file is part of Destroy All Vegans.
	http://dav.googlecode.com/

	Copyright (c) 2011 James C.

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the 'Software'), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "XMLLoader.h"
#include "tinyxml.h"
#include "tinystr.h"
#include <OgreRoot.h>
#include <OgreManualObject.h>
#include <OgreMath.h>

template<> DaV::XMLLoader* Ogre::Singleton<DaV::XMLLoader>::ms_Singleton = 0;

namespace DaV
{
	XMLLoader* XMLLoader::getSingletonPtr(void)
	{
		if(!ms_Singleton)
		{
			ms_Singleton = new XMLLoader();
		}

		assert(ms_Singleton);
		return ms_Singleton;
	}

	XMLLoader& XMLLoader::getSingleton(void)
	{
		if(!ms_Singleton)
		{
			getSingletonPtr();
		}
		assert(ms_Singleton);
		return (*ms_Singleton);
	}

	XMLLoader::XMLLoader(void)
	{
	}

	XMLLoader::~XMLLoader(void)
	{
	}

	void XMLLoader::destroy(void)
	{
		delete ms_Singleton;
	}

	XMLLoader::PlanetItems* XMLLoader::loadPlanet(const Ogre::String& name)
	{
		PlanetItems* pPlanet = new PlanetItems();
		Ogre::SceneManager* pSceneManager = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager");

		TiXmlDocument* pDocument = new TiXmlDocument();

		Ogre::String path = "../../Game/Media/objects/celestial/";
		path.append(name);
		path.append(".xml");

		assert(pDocument->LoadFile(path.c_str()));
		TiXmlElement* pElement = pDocument->FirstChildElement();

		if(strcmp(pElement->Value(),"planet") == 0)
		{
			pElement = pElement->FirstChildElement();

			do
			{
				Ogre::String tag = pElement->Value();
				if(strcmp(tag.c_str(),"model") == 0)
				{
					float radius = 10;
					int segments = 64;
					for(TiXmlElement* pSubEle = pElement->FirstChildElement(); pSubEle; pSubEle = pSubEle->NextSiblingElement())
					{
						tag = pSubEle->Value();
						if(strcmp(tag.c_str(),"radius") == 0)
						{
							radius = atof(pSubEle->FirstChild()->Value());
						}
						else if(strcmp(tag.c_str(),"segments") == 0)
						{
							segments = atoi(pSubEle->FirstChild()->Value());
						}
					}

					createSphere(name,radius,segments,segments);
					pPlanet->mpEntity = pSceneManager->createEntity(name,name);
				}
				else if(strcmp(tag.c_str(),"material") == 0)
				{
					for(TiXmlElement* pSubEle = pElement->FirstChildElement(); pSubEle; pSubEle = pSubEle->NextSiblingElement())
					{
						tag = pSubEle->Value();
						if(strcmp(tag.c_str(),"uninhabited") == 0)
						{
							pPlanet->mDefaultMaterial = pSubEle->FirstChild()->Value();
						}
						else if(strcmp(tag.c_str(),"terraformed") == 0)
						{
							pPlanet->mTerraformedMaterial = pSubEle->FirstChild()->Value();
						}
						else if(strcmp(tag.c_str(),"colonised") == 0)
						{
							pPlanet->mColonisedMaterial = pSubEle->FirstChild()->Value();
						}
					}
				}
				else if(strcmp(tag.c_str(),"state") == 0)
				{
					pPlanet->mState = atoi(pElement->FirstChild()->Value());
				}
			}while((pElement = pElement->NextSiblingElement()));

			pElement = NULL;
		}

		delete pDocument;
		return pPlanet;
	}

	XMLLoader::MoonItems* XMLLoader::loadMoon(const Ogre::String& name)
	{
		MoonItems* pMoon = new MoonItems();
		Ogre::SceneManager* pSceneManager = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager");

		TiXmlDocument* pDocument = new TiXmlDocument();

		Ogre::String path = "../../Game/Media/objects/celestial/";
		path.append(name);
		path.append(".xml");

		assert(pDocument->LoadFile(path.c_str()));
		TiXmlElement* pElement = pDocument->FirstChildElement();

		if(strcmp(pElement->Value(),"moon") == 0)
		{
			pElement = pElement->FirstChildElement();

			do
			{
				Ogre::String tag = pElement->Value();
				if(strcmp(tag.c_str(),"model") == 0)
				{
					float radius = 10;
					int segments = 64;
					for(TiXmlElement* pSubEle = pElement->FirstChildElement(); pSubEle; pSubEle = pSubEle->NextSiblingElement())
					{
						tag = pSubEle->Value();
						if(strcmp(tag.c_str(),"radius") == 0)
						{
							radius = atof(pSubEle->FirstChild()->Value());
						}
						else if(strcmp(tag.c_str(),"segments") == 0)
						{
							segments = atoi(pSubEle->FirstChild()->Value());
						}
					}

					createSphere(name,radius,segments,segments);
					pMoon->mpEntity = pSceneManager->createEntity(name,name);
				}
				else if(strcmp(tag.c_str(),"material") == 0)
				{
					pMoon->mDefaultMaterial = pElement->FirstChild()->Value();
				}
			}while((pElement = pElement->NextSiblingElement()));

			pElement = NULL;
		}

		delete pDocument;
		return pMoon;
	}

	void XMLLoader::createSphere(const Ogre::String& name, const float r, const int nRings, const int nSegments)
	{
		//Taken from http://www.ogre3d.org/tikiwiki/ManualSphereMeshes&structure=Cookbook
		Ogre::SceneManager* pSceneManager = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager");
		Ogre::ManualObject* manual = pSceneManager->createManualObject(name);
		manual->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
 
		float fDeltaRingAngle = (Ogre::Math::PI / nRings);
		float fDeltaSegAngle = (2 * Ogre::Math::PI / nSegments);
		unsigned short wVerticeIndex = 0;
 
		// Generate the group of rings for the sphere
		for(int ring = 0; ring <= nRings; ring++)
		{
			float r0 = r * sinf (ring * fDeltaRingAngle);
			float y0 = r * cosf (ring * fDeltaRingAngle);
 
			// Generate the group of segments for the current ring
			for(int seg = 0; seg <= nSegments; seg++)
			{
				float x0 = r0 * sinf(seg * fDeltaSegAngle);
				float z0 = r0 * cosf(seg * fDeltaSegAngle);
 
				// Add one vertex to the strip which makes up the sphere
				manual->position(x0, y0, z0);
				manual->normal(Ogre::Vector3(x0, y0, z0).normalisedCopy());
				manual->textureCoord((float) seg / (float) nSegments, (float) ring / (float) nRings);
 
				if(ring != nRings)
				{
					// each vertex (except the last) has six indicies pointing to it
					manual->index(wVerticeIndex + nSegments + 1);
					manual->index(wVerticeIndex);               
					manual->index(wVerticeIndex + nSegments);
					manual->index(wVerticeIndex + nSegments + 1);
					manual->index(wVerticeIndex + 1);
					manual->index(wVerticeIndex);
					wVerticeIndex ++;
				}
			}; // end for seg
		} // end for ring
		manual->end();
		Ogre::MeshPtr mesh = manual->convertToMesh(name);
		mesh->_setBounds( Ogre::AxisAlignedBox( Ogre::Vector3(-r, -r, -r), Ogre::Vector3(r, r, r) ), false );
 
		mesh->_setBoundingSphereRadius(r);
		unsigned short src, dest;
		if(!mesh->suggestTangentVectorBuildParams(Ogre::VES_TANGENT, src, dest))
		{
			mesh->buildTangentVectors(Ogre::VES_TANGENT, src, dest);
		}
	}
}